package com.wzx.user.sdk.controller;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alipay.api.*;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.wzx.common.exception.LeadNewsException;
import com.wzx.common.pojo.resp.Result;
import com.wzx.user.vo.PayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;

/**
 * @author wzx
 * @version 1.0
 * @date 2023/2/28 - 21:03
 * @description 标题
 */
@Slf4j
@RestController
@RequestMapping("/zfb")
public class ZfbController {

    public final String RSA2 = "RSA2";
    public final String CHARSET = "UTF-8";

    /*private String URL = "https://openapi.alipay.com/gateway.do";
    private String APPID = "2021003181612006";
    private String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCP7Le7ZlBimmVtzyBP4W2J95ZixccMaZcj7uuDCvOKaMczF2/n6h9RGax+VT7l9uxkA6zaKN2o31ZN82kKlikGPAMvQierfYyNLVDPfJY6Jn3qUgwNPCqR5BMa/cJ43eNSSLH/YVX10ekxOmem5Zait+13ntxZx/5I3WDIQmzYMi9GmruPJHX54wBjlcWQcY4feXokvVn96V6TP1brOyVYgI7FX/pqluxGpG4s3j13VjmAp9T02JrFGU4HHdb0JqHrNIo7+W1aHnbRDyPRH2+4jiMmUSFKwdv1nmBaw/BRDoKBZwahyPMntHoPVNkjigC3TC9OVHhtlXbyWHh4LL9LAgMBAAECggEARWMuwV52atNdCy/MuDZKhTWkf0Iy0L0nbN+HE8p318bkIrGt9fVd28+w5cdbZ6tAFIfhEdyZ4QyrozEy9zOl26ebMXGHhpok5Ptv9lhuZOKh2hJsVQUo0OVQgLbOx07ShZ0ek6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fT2Akf2w=";
    private String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj14KRR7giITxMXzbgrFjxSQ2TSfkKYn48c8p+DBJ4Pcs3vwjsRgJ5FEN8J6U0km3I/BaBenJXE8e5CR0bso6SxBJR20kRmX68zKqKHKyqczQYxZa253N0Rszap8faseahFKoZwb7BiglKEez9bDfEJ0LCWvM8OcKfTtT2fAUXJJIC2HowK5YptX98qujIPwIWENdKeAGPgpoMU7joWcf/xEF32570DYlveGC7bxozeH4kaDGbTfW1Udv+TjIGT4FFFRsl4dyPbx4sdiqSCI9HMPs6k7oMZf3vXkp6K9OoQenEsKNPfQTov9FbI0MAnuEy6UvlJzPXjPWksm5yerEzQIDAQAB";*/

    @Value("${zfbPay.url}")
    private String URL;

    @Value("${zfbPay.appId}")
    private String APPID;

    @Value("${zfbPay.appPrivateKey}")
    private String APP_PRIVATE_KEY;

    @Value("${zfbPay.alipayPublicKey}")
    private String ALIPAY_PUBLIC_KEY;

    @Value("${zfbPay.appCertPublicKey}")
    private String APP_CERT_PUBLIC_KEY;

    @Value("${zfbPay.alipayCertPublicKey}")
    private String ALIPAY_CERT_PUBLIC_KEY;

    @Value("${zfbPay.alipayRootCertPath}")
    private String ALIPAY_ROOT_CERT_PATH;


    /**
     * 用授权码获取 access_token, user_id
     * 官方文档: https://opendocs.alipay.com/open/02ailc
     */
    //@GetMapping("/get1")
    private AlipaySystemOauthTokenResponse getAccessToken(String autoCode) throws AlipayApiException {

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(URL);
        certAlipayRequest.setAppId(APPID);
        //应用私钥
        certAlipayRequest.setPrivateKey(APP_PRIVATE_KEY);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset(CHARSET);
        certAlipayRequest.setSignType("RSA2");
        // 设置应用公钥证书路径
        certAlipayRequest.setCertPath(APP_CERT_PUBLIC_KEY);
        // 设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(ALIPAY_CERT_PUBLIC_KEY);
        // 设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(ALIPAY_ROOT_CERT_PATH);
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");//请求参数 grant_type
        request.setCode(autoCode);//请求参数,授权码 code
        // request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");//请求参数 refresh_token
        AlipaySystemOauthTokenResponse response = alipayClient.certificateExecute(request);

        System.err.println("返回的信息: " + response.getBody());

        if (response.isSuccess()) {
            System.out.println("获取access_token成功");
            return response;
        } else {
            System.out.println("获取access_token失败");
            return null;
        }
    }

    /**
     * 获取支付宝用户信息
     * 官方文档: https://opendocs.alipay.com/open/02aild
     */
    ////@GetMapping("/get2")
    private AlipayUserInfoShareResponse getAliUserInfo(String accessToken) throws Exception {

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(URL);
        certAlipayRequest.setAppId(APPID);
        //应用私钥
        certAlipayRequest.setPrivateKey(APP_PRIVATE_KEY);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset(CHARSET);
        certAlipayRequest.setSignType("RSA2");
        // 设置应用公钥证书路径
        certAlipayRequest.setCertPath(APP_CERT_PUBLIC_KEY);
        // 设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(ALIPAY_CERT_PUBLIC_KEY);
        // 设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(ALIPAY_ROOT_CERT_PATH);
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response = alipayClient.certificateExecute(request, accessToken);
        System.err.println("response = " + response);
        if (response.isSuccess()) {
            System.out.println("获取用户信息成功");
            return response;
        } else {
            System.out.println("获取用户信息失败");
            return null;
        }
    }

    /*@PostMapping("/getPayment")
    public Result<String> getPayment(@RequestBody PayVo payVo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(URL,
                APPID,APP_PRIVATE_KEY,"json",
                "UTF-8",ALIPAY_PUBLIC_KEY,"RSA2");

        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl("");
        JSONObject bizContent = new JSONObject();

        //获取当前时间
        //Date date = new Date();
        String format = DateUtils.format(new Date(), DateUtils.DATE_FORMAT_14);

        bizContent.put("out_trade_no",format + "00000");
        bizContent.put("total_amount", payVo.getPrice());
        bizContent.put("subject", "用户下订单");
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        // 商品明细信息，按需传入
        *//*JSONArray goodsDetail = new JSONArray();
        JSONObject goods1 = new JSONObject();
        goods1.put("goods_id", payVo.getOrderId());*//*
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        *//*goodsDetail.add(goods1);
        bizContent.put("goods_detail", goodsDetail);*//*

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        if(response.isSuccess()){
            log.info("生成订单信息成功！");
            return Result.ok(response.getBody());
        } else {
            log.info("生成订单信息失败！");
            return Result.error("生成订单信息错误！");
        }
    }*/

    @PostMapping("/getPayment")
    public Result<String> getPayment(@RequestBody PayVo payVo) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(URL);
        certAlipayRequest.setAppId(APPID);
        //应用私钥
        certAlipayRequest.setPrivateKey(APP_PRIVATE_KEY);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset(CHARSET);
        certAlipayRequest.setSignType("RSA2");
        // 设置应用公钥证书路径
        certAlipayRequest.setCertPath(APP_CERT_PUBLIC_KEY);
        // 设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(ALIPAY_CERT_PUBLIC_KEY);
        // 设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(ALIPAY_ROOT_CERT_PATH);

        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //我的接口（APP支付TRADE_SUCCESS（交易成功）、TRADE_CLOSED（交易关闭）、TRADE_FINISHED（交易完成）三种状态均会触发异步通知）
        request.setNotifyUrl("");

        JSONObject bizContent = new JSONObject();

        //获取当前时间
        //Date date = new Date();
        String format = DateUtils.format(new Date(), DateUtils.DATE_FORMAT_14);
        bizContent.put("out_trade_no", format + "00000");
        bizContent.put("total_amount", payVo.getPrice());
        bizContent.put("subject", "用户下订单");
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        if (response.isSuccess()) {
            log.info("生成订单信息成功！");
            return Result.ok(response.getBody());
        } else {
            log.info("生成订单信息失败！");
            return Result.error("生成订单信息错误！");
        }
    }

    //@GetMapping("/test")
    public Result<String> test() throws AlipayApiException {
        AlipayFundTransUniTransferResponse response = null;
        try {
            CertAlipayRequest alipayConfig = new CertAlipayRequest();
            alipayConfig.setPrivateKey(APP_PRIVATE_KEY);
            alipayConfig.setServerUrl(URL);
            alipayConfig.setAppId(APPID);
            alipayConfig.setCharset("UTF8");
            alipayConfig.setSignType("RSA2");
            alipayConfig.setEncryptor("");
            alipayConfig.setFormat("json");
            // 设置应用公钥证书路径
            alipayConfig.setCertPath(APP_CERT_PUBLIC_KEY);
            // 设置支付宝公钥证书路径
            alipayConfig.setAlipayPublicCertPath(ALIPAY_CERT_PUBLIC_KEY);
            // 设置支付宝根证书路径
            alipayConfig.setRootCertPath(ALIPAY_ROOT_CERT_PATH);
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            String format = DateUtils.format(new Date(), DateUtils.DATE_FORMAT_14);
            model.setOutBizNo(format);
            SignData signData = new SignData();
            signData.setOriOutBizNo("商户订单号");
            signData.setOriSignType("RSA2");
            signData.setOriSign("EqHFP0z4a9iaQ1ep==");
            signData.setOriCharSet("UTF-8");
            signData.setPartnerId("18823743360");
            signData.setOriAppId("2021000185629012");
            model.setSignData(signData);
            model.setRemark("单笔转账");
            model.setOriginalOrderId("20190620110075000006640000063056");
            model.setBusinessParams("{\"sub_biz_scene\":\"REDPACKET\"}");
            model.setBizScene("DIRECT_TRANSFER");
            Participant payeeInfo = new Participant();
            payeeInfo.setIdentity("testaccount@alipay.com");
            payeeInfo.setIdentityType("ALIPAY_OPEN_ID");
            payeeInfo.setName("黄龙国际有限公司");
            model.setPayeeInfo(payeeInfo);
            model.setTransAmount("23.00");
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            model.setOrderTitle("转账标题");
            request.setBizModel(model);
            response = alipayClient.certificateExecute(request);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

        return Result.ok(response.getBody());
    }


    //@GetMapping("/gettest")
    public void gettest() throws AlipayApiException {
        CertAlipayRequest alipayConfig = new CertAlipayRequest();
        alipayConfig.setPrivateKey(APP_PRIVATE_KEY);
        alipayConfig.setServerUrl(URL);
        alipayConfig.setAppId(APPID);
        alipayConfig.setCharset("UTF8");
        alipayConfig.setSignType("RSA2");
        alipayConfig.setEncryptor("");
        alipayConfig.setFormat("json");
        // 设置应用公钥证书路径
        alipayConfig.setCertPath(APP_CERT_PUBLIC_KEY);
        // 设置支付宝公钥证书路径
        alipayConfig.setAlipayPublicCertPath(ALIPAY_CERT_PUBLIC_KEY);
        // 设置支付宝根证书路径
        alipayConfig.setRootCertPath(ALIPAY_ROOT_CERT_PATH);

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
        model.setOutBizNo("201806300001");
        model.setRemark("201905代发");
        model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
        model.setBizScene("DIRECT_TRANSFER");
        Participant payeeInfo = new Participant();
        payeeInfo.setIdentity("18823743360");
        payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
        payeeInfo.setName("王子贤");
        model.setPayeeInfo(payeeInfo);
        model.setTransAmount("0.1");
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");
        model.setOrderTitle("201905代发");
        request.setBizModel(model);
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

    }


}
